<?php
/**
 * Created by 上海风车教育科技有限公司.
 * User: 刘红伟
 * Date: 15-12-22
 * Email: 454303753@qq.com
 * File:wx_notify_template.php
 */
class wx_notify_template{
    private $parameter;
    private  $token;
    public function __construct($data=array()){

        $this->parameter=$data;
    }

    public function send(){

        if(Yii::app()->params['redis_on_off']){
            $cache_accessToken=  Yii::app()->cache->getValue('cache_accessToken_key');
            $cache_accessTokenTime=  Yii::app()->cache->getValue('cache_accessToken_time');

            if(!empty($cache_accessToken) && !empty($cache_accessTokenTime)   && (time()-$cache_accessTokenTime<Yii::app()->params['redis_expires'])){

                $this->token=$cache_accessToken;

            }else{

                $token_odj=   new wechataccesstoken(Yii::app()->params['APPID'],Yii::app()->params['secret']);
                $token_array= $token_odj->get();

                if($token_array){
                    Yii::app()->cache->setValue('cache_accessToken_key',$token_array['access_token'],7000);
                    Yii::app()->cache->setValue('cache_accessToken_time',time()+$token_array['expires_in'],7000);

                    $this->token=$token_array['access_token'];
                }

            }

        }else{
            $token_data= Yii::app()->db->createCommand()->from('token')->order('id desc')->limit(1)->queryRow();

            if($token_data){

                if(time()-$token_data['add_time']<7000){
                    $this->token=$token_data['token'];
                }else{
                    $token_odj=   new wechataccesstoken(Yii::app()->params['APPID'],Yii::app()->params['secret']);
                    $token_array= $token_odj->get();
                    if($token_array){
                        $this->token=$token_array['access_token'];

                        Yii::app()->getDb()->createCommand()->insert('token', array(
                            'token' => $token_array['access_token'],
                            'add_time' => time()+$token_array['expires_in']
                        ));

                    }
                }
            }else{

                $token_odj=   new wechataccesstoken(Yii::app()->params['APPID'],Yii::app()->params['secret']);
                $token_array= $token_odj->get();

                if($token_array){
                    $this->token=$token_array['access_token'];
                    Yii::app()->getDb()->createCommand()->insert('token', array(
                        'token' => $token_array['access_token'],
                        'add_time' => time()+$token_array['expires_in']
                    ));
                }
            }

        }

        $temapi=  new wechattemplateapi($this->token,$this->parameter,1);
        $temapi->send();//通知不成功，未做记录
    }
}